<template>
  <div class="tea-account">
    <h5 class="subtitle">最后一步</h5>
    <cube-form :model="model" @validate="validateHandler" @submit="submitHandler">
      <cube-form-group>
        <cube-form-item :field="fields[0]"></cube-form-item>
      </cube-form-group>
      <cube-form-group class="subBtn">
        <cube-button @click="goback" :inline="true" :primary="true">上一步</cube-button>
        <cube-button type="submit" :inline="true" :primary="true">提交</cube-button>
      </cube-form-group>
    </cube-form>
  </div>
</template>

<script>
export default {
  name: "TeaAccount",
  data() {
    return {
      validity: {},
      valid: undefined,
      model: {
        account: ""
      },
      fields: [
        {
          type: "input",
          modelKey: "account",
          label: "账号",
          props: {
            placeholder: "请输入账号"
          },
          rules: {
            required: true
          },
          // validating when blur
          trigger: "blur"
        }
      ],
      content: ""
    };
  },
  created() {
    if (
      localStorage.getItem("openID") == "" &&
      localStorage.getItem("openID") == null
    ) {
      this.getCode();
    }
  },
  methods: {
    getUrlKey(name) {
      //获取url 参数
      return (
        decodeURIComponent(
          (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
            location.href
          ) || [, ""])[1].replace(/\+/g, "%20")
        ) || null
      );
    },
    getCode() {
      const code = this.getUrlKey("code"); // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
      const local = window.location.href;
      const appid = "wx6d7dcd07ca4fa211";
      if (code == null || code === "") {
        window.location.href =
          "http://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
          appid +
          "&redirect_uri=" +
          encodeURIComponent(local) +
          "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
      } else {
        this.getOpenId(code); //把code传给后台获取用户信息
      }
    },
    getOpenId(code) {
      // 通过code获取 openId等用户信息，/oauth2/printOpenID 为后台接口
      this.$http
        .post("/oauth2/printOpenID", { code: code })
        .then(res => {
          let openID = res.data;
          this.$store.state.openID = openID;
          localStorage.setItem("openID", openID);
        })
        .catch(error => {
          console.log(error);
        });
    },
    validateHandler(result) {
      this.validity = result.validity;
      this.valid = result.valid;
    },
    submitHandler(e) {
      e.preventDefault();
      this.$store.state.account = this.model.account;
      // console.log(localStorage.getItem("schoolId"));
      let requestData = {
        schoolId: this.$route.query.schoolId,
        account: this.$store.state.account
      };
      // console.log(requestData);
      this.getTeaInfor(requestData);
    },
    // 获取绑定的老师信息
    getTeaInfor(requestData) {
      this.$http
        .post("/api000015", requestData)
        .then(response => {
         
          // <!-- 账号查找不到老师信息 -->
          if (response.data.id == 0 || response.data.id == null) {
            this.$createToast({
              type: "warn",
              txt: "暂无该账号信息，请检查您输入的账号是否有误",
              mask: true
            }).show();
          } else {
            // 账号查找到了老师信息
            // 有老师信息，并且有openID（已绑定微信状态）（这里应该后台判断当前使用的openID与数据库存储的openID是否一致）
            if (response.data.openID != null && response.data.openID != "") {
              this.$store.state.openID = response.data.openID;
              localStorage.setItem("openID", response.data.openID);
              this.$createToast({
                type: "warn",
                txt: "关系已绑定，即将跳转到已发布的作业列表",
                mask: true
              }).show();
              setTimeout(() => {
                this.$router.push({
                  path: "/teajoblist"
                });
              }, 1000);
            } else {
              // 有老师信息，但是没有openID（未绑定微信状态）
              this.content = response.data.teacherName;
              this.$createDialog({
                type: "confirm",
                icon: "cubeic-alert",
                title: "您将绑定的教师姓名为",
                content: `${this.content}`,
                confirmBtn: {
                  text: "确定",
                  active: true,
                  disabled: false,
                  href: "javascript:;"
                },
                cancelBtn: {
                  text: "取消",
                  active: false,
                  disabled: false,
                  href: "javascript:;"
                },
                onConfirm: () => {
                  let request = {
                    openId: this.$store.state.openID,
                    schoolId: response.data.school_id,
                    account: this.$store.state.account
                  };
                  this.confirmBind(request);
                },
                onCancel: () => {
                  this.$createToast({
                    type: "warn",
                    time: 1000,
                    txt: "取消绑定"
                  }).show();
                }
              }).show();
            }
          }
        })
        .catch(error => {
          this.$createToast({
            type: "warn",
            time: 1000,
            txt: error
          }).show();
        });
    },
    // 确认绑定
    confirmBind(requestData) {
      this.$http
        .post("/api000016", requestData)
        .then(response => {
          // this.$store.state.openID = response.data.openID;
          // localStorage.setItem("openID", response.data.openID);
          this.$createToast({
            type: "loading",
            time: 0,
            txt: "即将跳转到已发布的作业列表"
          }).show();
          setTimeout(() => {
            this.$router.push({
              path: "/teajoblist"
            });
          }, 1000);
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    goback() {
      this.$router.push({
        path: "/teaadd/school",
        query: {
          area: this.$route.query.area,
          school: this.$route.query.school
        }
      });
    }
  }
};
</script>

<style lang="scss">
.tea-account {
  .subtitle {
    font-size: 16px;
    font-weight: 700;
    color: #fc9153;
    margin-top: 20%;
    margin-bottom: 10%;
    text-align: center;
  }
  .subBtn {
    margin: 5% auto;
    text-align: center;
    margin-top: 20%;
    button {
      width: 40%;
      margin: 2%;
    }
  }
}
</style>